package com.cise.searcher;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.lucene.index.IndexReader;

import com.cise.searcher.utils.Result;
import com.cise.sort.AbstractSort;
import com.cise.sort.utils.AbstractResult;
import com.cise.utils.Util;

public abstract class AbstractParallelSearcher implements SearcherThread.CallBack{
	protected List<String> indexPaths = null;
	protected AbstractSort sort = null;
	private ArrayList<Result[]> results = new ArrayList<Result[]>();
	private CountDownLatch count;
	private ExecutorService pool = Executors.newFixedThreadPool(Util.THREAD_POOL_MAX_SIZE);

	public List<Result> search(BufferedImage img) {
		IndexReader ir;
		try {
			if (this.sort == null || img == null || null == this.indexPaths || this.indexPaths.size() == 0) {
				return null;
			} else {
				this.count = new CountDownLatch(this.indexPaths.size());
				System.out.println("开始搜索时间：" + new Date(System.currentTimeMillis()));
				for (int i = 0; i < this.indexPaths.size(); i++) {
					SearcherThread searcherThread = new SearcherThread(img, 
							Util.INDEX_ROOT_PATH + this.indexPaths.get(i) + File.separator, 
							this.pool, this.indexPaths.get(i), this);
					this.pool.execute(searcherThread);
				}
				this.count.await();
				this.pool.shutdown();
				System.out.println("搜索结束时间：" + new Date(System.currentTimeMillis()));
				ArrayList<AbstractResult[]> abstractResults = new ArrayList<AbstractResult[]>(results.size());
				for(int i = 0; i < results.size(); i++){
					abstractResults.add(com.cise.searcher.utils.Util.convertType(results.get(i)));
				}
				return com.cise.searcher.utils.Util.convertType(this.sort.sort(abstractResults));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		return null;
	}

	public List<String> getIndexPaths() {
		return this.indexPaths;
	}

	public void setIndexPaths(List<String> indexPaths) {
		this.indexPaths = indexPaths;
	}

	@Override
	public void setResult(AbstractResult[] iResults) {
		this.results.add(com.cise.searcher.utils.Util.convertType(iResults));
		this.count.countDown();
	}
	
}
